// 利用tcp 协议自己来实现websocket的连接

import net from "net";
import crypto from "crypto";

const server = net.createServer((socket) => {
  // 第一次发过来的信息是协议升级
  socket.once("data", function (data) {
    data = data.toString();
    if (data.match(/Upgrade: websocket/)) {
      // 升级协议
      const headers = data
        .split("\r\n")
        .slice(1, -2)
        .reduce((memo, row) => {
          let [key, value] = row.split(": ");
          memo[key.toLowerCase()] = value;
          return memo;
        }, {});
      const webSocketKey = headers["sec-websocket-key"];
      const number = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; // 死制
      let websocketAccept = crypto
        .createHash("sha1")
        .update(webSocketKey + number)
        .digest("base64");

      let responseText = [
        "HTTP/1.1 101 Switching Protocols",
        "Connection: Upgrade",
        "Upgrade: websocket",
        `Sec-Websocket-Accept: ${websocketAccept}`,
        `\r\n`,
      ].join("\r\n");
      socket.write(responseText);

      socket.on("data", function (buffer) {
        // 88 一个字节  8 个位， 我怎么知道第一个位的值是不是1

        const FIN = (buffer[0] & 0b10000000) === 0b10000000; // 利用&的特点都是1才是1
        // 101010101
        // 0b00000010
        const OPCODE = buffer[0] & 0b00001111; // 00000010

        const MASK = (buffer[1] & 0b10000000) === 0b10000000;
        console.log(FIN, OPCODE, MASK);

        const PAYLOAD_LEN = buffer[1] & 0b01111111; // 00000010

        const maskedKey = buffer.slice(2, 6);

        const responseData = buffer.slice(6); // 内容 经过掩码的

        for (let i = 0; i < PAYLOAD_LEN; i++) {
          // maskedKey = 4  responseData = 100
          responseData[i] = responseData[i] ^ maskedKey[i % 4]; // 做了掩码后的处理
        }
        console.log(responseData.toString());
        // 100000000 &
      });
    }
  });
});
server.listen(3000);
// import { WebSocketServer } from "ws";

// const wss = new WebSocketServer({ port: 3000 });
// wss.on("connection", function (ws) {
//   ws.on("message", (data) => {
//     console.log(data.toString(), 6);
//   });
//   ws.send("hello client");

//   ws.on("error", function (err) {
//     console.log(err);
//   });
// });

// 1. 我们先三次握手
// 2.发送get 请求
// Sec-Websocket-Version: 13
// Upgrade: websocket
// Connection: Upgrade
// Sec-Websocket-Key: LiViAMiJD0r/9+K7uChD1A==  随机的

// Connection: Upgrade
// Sec-Websocket-Accept: NbdbUJWWvepHu9gvvxPFqZUv3a4=
// Upgrade: websocket

// import crypto from "crypto";
// const number = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; // 死制
// const webSocketKey = "LiViAMiJD0r/9+K7uChD1A==";
// let websocketAccept = crypto
//   .createHash("sha1")
//   .update(webSocketKey + number)
//   .digest("base64");
// console.log(websocketAccept);
